package com.honvay.cola.cloud.framework.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;

/**
 * 小程序AES解密
 */
public class AESDecodeUtils {

    public static void main(String[] args) throws Exception {
//        byte[] encrypData = Base64.decodeBase64("mgxuts7uEbdnBclp0Qim0TS3MGoaSyE09MqTvbeG9Z1PjxsDwjVH0FxG1Q==");
//        byte[] ivData = Base64.decodeBase64("SG386etdA3sOXHxqfnw==");
//        byte[] sessionKey = Base64.decodeBase64("Fn6r4IOiZJBXn4hQ0w==");
//        System.out.println(decrypt(sessionKey, ivData, encrypData));
        String value = "{" +
                "\"OperatorID\": \"326400952\"," +
                "\"OperatorSecret\": \"1234567890abcdef\"" +
                "}";

        System.out.println(value);
        String encrypt = encrypt("1234567890abcdef", "1234567890abcdef", value);
        System.out.println(encrypt);
    }

    /**
     * 解密
     *
     * @param key
     * @param iv
     * @param encData
     * @return
     * @throws Exception
     */
    public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        //解析解密后的字符串
        return new String(cipher.doFinal(encData), "UTF-8");
    }


    /**
     * 加密
     *
     * @param key
     * @param initVector
     * @param value
     * @return
     */
    public static String encrypt(String key, String initVector, String value) {
        try {
            System.out.println("key:\t" + Arrays.toString(key.getBytes("UTF-8")));
            System.out.println("iv:\t" + Arrays.toString(initVector.getBytes("UTF-8")));
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            //Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            byte[] encrypted = cipher.doFinal(value.getBytes());
            System.out.println(Arrays.toString(encrypted));
            System.out.println("encrypted string: "
                    + Base64.encodeBase64String(encrypted));

//            return byte2HexStr(encrypted);
            return Base64.encodeBase64String(encrypted);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

}
